package com.msi.shortwave;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class station extends Fragment {
	
	private Button b1;
	private Button searchbutton;
	private TextView timedisplay;
	static final int TIME_DIALOG_ID = 0;
	private String selhour;
	private String selmin;
	private String selstation = "";
	private String selstationid ="";
	String sellang;
	public ArrayList<String> stationids = new ArrayList<String>();
	public ArrayList<String> stationnames = new ArrayList<String>();
	public ArrayList<String> langids = new ArrayList<String>();
	
	

	
	public void onResume()
	{

		super.onResume();
		 AutoCompleteTextView autocompletetextview;
          autocompletetextview = (AutoCompleteTextView) getActivity().findViewById(R.id.stationauto);
          autocompletetextview.setText("");
		if (selstationid !="" && selstation !=""){
		Spinner s = (Spinner) getActivity().findViewById(R.id.stationspin);
		//s.setSelection(Integer.valueOf(selstationid));
		selstation = selstationid;
		}
	}
	
	   @Override
	   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	      // Inflate the layout for this fragment
		   stationids.clear();
	      View v = inflater.inflate(R.layout.station, container, false);
	      Spinner s = (Spinner) v.findViewById(R.id.stationspin);
	      final ArrayAdapter<String> adapterForSpinner = new ArrayAdapter<String>(getActivity(),
	        		android.R.layout.simple_spinner_item);
      		                adapterForSpinner.setDropDownViewResource
      		(android.R.layout.simple_spinner_dropdown_item);
      		                s.setAdapter(adapterForSpinner); 
      		              AutoCompleteTextView autocompletetextview;
 
      		              autocompletetextview = (AutoCompleteTextView) v.findViewById(R.id.stationauto);
      		            autocompletetextview.setAdapter(adapterForSpinner);
      		              
      		              s.setOnItemSelectedListener(new OnItemSelectedListener() {
      		                  @Override


      		              	public void onItemSelected(AdapterView<?> parent,
      		              	 View view, int pos, long id) {
      		                  	
      		              	selstation = Integer.toString(pos);
      		              
      		              		    		//do something
      		              		    			    	}
      		                  						@Override

      		              	public void onNothingSelected(AdapterView<?> parent) {
      		              		// Do nothing.
      		              	  }
      		              		    			});
      		              
      		              		                
      		           	SQLiteDatabase myDB= null;
      		      	        	
      		      	    myDB = getActivity().openOrCreateDatabase("shortwave", getActivity().MODE_PRIVATE, null);
      		          	Cursor c = myDB.rawQuery("SELECT name, id FROM stations ORDER BY name ASC ;",null);
      		          	
      		              if(c.moveToFirst()){
      		                  do{
      		                  	adapterForSpinner.add(c.getString(0));
      		                  	stationids.add(c.getString(1));
      		                  	stationnames.add(c.getString(0));

      		                  } while(c.moveToNext()); }

      		              c.close();
      		            
      		              
      		            SimpleDateFormat f = new SimpleDateFormat("HH");
      		      	f.setTimeZone(TimeZone.getTimeZone("UTC"));
      		      	
      		          SimpleDateFormat m = new SimpleDateFormat("mm");
      		      	m.setTimeZone(TimeZone.getTimeZone("UTC"));
      		      	
      		      	
      		      	TimePicker timeselect = (TimePicker) v.findViewById(R.id.timepicker);
      		      	
      		      	timeselect.setIs24HourView(true);
      		      	timeselect.setCurrentHour(Integer.valueOf(f.format(new Date())));
      		      	timeselect.setCurrentMinute(Integer.valueOf(m.format(new Date())));
      		      	timeselect.setEnabled(false);
      		      

      		      	searchbutton = (Button) v.findViewById(R.id.bsearchtimestation);
      		                
      		  
	      
      		      searchbutton.setOnClickListener(new View.OnClickListener() {
      		    	public void onClick(View v) {
      		        	TimePicker timeselect = (TimePicker) getActivity().findViewById(R.id.timepicker);

      		         	final CheckBox checkbox = (CheckBox) getActivity().findViewById(R.id.stationcheck);

      		        	if (checkbox.isChecked()){
      		        		String strmin =  Integer.toString(timeselect.getCurrentMinute());
      		    			String strhour =  Integer.toString(timeselect.getCurrentHour());
      		    			if (strmin.length() == 1){
      		    			strmin = "0" + strmin;
      		    			}
      		    			if (strhour.length() == 1){
      		    				strhour = "0" + strhour;
      		    				}
      		    			
      		    		selmin = strmin;
      		    		selhour = strhour;		
      		        	}

  		        	
      		    	 //Intent myIntent = new Intent(getActivity(), results.class);
      		    	//Fragment mFragmentR = (Fragment) new results();
      		         	
      		         	
      		    	FragmentTransaction ft = getFragmentManager().beginTransaction();

      		    	Fragment mFragmentR=new results ();
      				Spinner mySpn = (Spinner) getActivity().findViewById(R.id.stationspin);

      		    	if (mySpn.getCount() < 1) {
      					Toast.makeText(getActivity(), "Please select a station",
      					   Toast.LENGTH_SHORT).show();
        		          return;
      				}

      				String spnItemStation = mySpn.getSelectedItem().toString();
      				
      				
      				selstation = stationids.get(stationnames.indexOf(spnItemStation));
      				
      				
      				mySpn = (Spinner) getActivity().findViewById(R.id.langspinstation);
      				int spnItem = mySpn.getSelectedItemPosition();
      				sellang = langids.get(spnItem);
      				
      		    	
      		    	
     		 
      		    	 Bundle bund1 =  new Bundle();
					bund1.putString("station", selstation);
					
      		    	bund1.putString("time", selhour+selmin);
      		    	bund1.putString("target", "");
      		    	bund1.putString("freq", "");
      		    	bund1.putString("language", sellang);
      		    	Log.i("SW2",bund1.toString());
					mFragmentR.setArguments(bund1);
					  if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
					        ft.replace(R.id.fragment_content2, mFragmentR, null);
					    }else if((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     

					        ft.replace(R.id.fragment_content2, mFragmentR, null);
					    }else{
      		    	ft.replace(R.id.fragment_content, mFragmentR, null);
					    }
					ft.addToBackStack(null);

					ft.commit();
      		    	 
      		    	 
      		    	
      		    
      		    	 
      		    	
      		    	// startActivity(myIntent);
      		    	}});
      		      
      		    
				langids.add("999");
      		    langids.add("");

      			Spinner langspinner = (Spinner) v.findViewById(R.id.langspinstation);
      			ArrayAdapter<String> adapterForLangSpinner = new ArrayAdapter<String>(getActivity(),
      	        		android.R.layout.simple_spinner_item);
      	  		                adapterForSpinner.setDropDownViewResource
      	  		(android.R.layout.simple_spinner_dropdown_item);
      	  		              adapterForLangSpinner.add(getString(R.string.anylanguage));
      	  		            adapterForLangSpinner.add(getString(R.string.notvoicelanguage));
      	  		            langspinner.setAdapter(adapterForLangSpinner); 
      		    
      	  		         	
      		      	        	
      	  		          c = myDB.rawQuery("SELECT language, code FROM languages;",null);
      	  		          	
      	  		              if(c.moveToFirst()){
      	  		                  do{
      	  		                	adapterForLangSpinner.add(c.getString(0));
      	  		                  	langids.add(c.getString(1));
      	  		                  } while(c.moveToNext()); }

      	  		              c.close();
      	  		              myDB.close();
      	  		              
      	  		              
      	  		              
      	  		     langspinner.setOnItemSelectedListener(new OnItemSelectedListener() {


      			    public void onItemSelected(AdapterView<?> parent,
      			        View view, int pos, long id) {
      			    	
      			    	
      			    
      			     	sellang = Integer.toString(pos);
      			    
      			    	
      			   
      			    }

      			    public void onNothingSelected(AdapterView<?> parent) {
      			      // Do nothing.
      			    }
      			
      		    });
	      
	      final CheckBox checkbox = (CheckBox) v.findViewById(R.id.stationcheck);
	    	checkbox.setOnClickListener(new View.OnClickListener() {
	    	    public void onClick(View v) {
    	         	TimePicker timeselect2 = (TimePicker) getActivity().findViewById(R.id.timepicker);

	    	        // Perform action on clicks, depending on whether it's now checked
	    	        if (((CheckBox) v).isChecked()) {
	    	        	timeselect2.setEnabled(true);
	    	            SimpleDateFormat f = new SimpleDateFormat("HHmm");
	    	        	f.setTimeZone(TimeZone.getTimeZone("UTC"));
	    	        	selhour = (f.format(new Date()).substring(0,2));
	    	        	selmin = (f.format(new Date()).substring(2,4));
	    	        } else {
	    	        	timeselect2.setEnabled(false);
	    	        	selmin = "";
	    	        	selhour = "";
	    	        }
	    	    }
	    	});
	    	  return v;
	   }
	   
	   public station() {

	   }
	        
	}